import NProgress from 'nprogress'
import router from './routes'
import store from './vuex/store'
import { Message } from 'element-ui'
import 'nprogress/nprogress.css'
NProgress.configure({ showSpinner: false })
const whiteList = ['/login', "/register"]

function hasPermission(roles, permissionRoles) {
    if (roles.indexOf('admin') >= 0 || roles.indexOf("super_editor") >= 0) return true // 管理或者超级管理都有全部权限
    if (!permissionRoles) return true     // 改路由没有权限要求则放行
    return roles.some(role => permissionRoles.indexOf(role) >= 0)  // 当前用户是否有该路由权限
}


router.beforeEach((to, from, next) => {
    NProgress.start()
    let token = localStorage.JWT_TOKEN

    if (token) {
        /* has token*/
        if (to.path === '/login') {
            next()
            // next({ path: '/' }) // 重新发送路由即会触发beforeEach，如果path: '/login' 则死循环
            NProgress.done()
        } else {
            if (store.getters.roles.length === 0) {

                store.dispatch('getUserInfo').then(() =>{
                    const roles = store.getters.roles
                    store.dispatch('GenerateRoutes', { roles }).then(() => { // 根据roles权限生成可访问的路由表
                        router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
                        next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
                    })
                }).catch((err) => {
                    Message.error(err || 'Verification failed, please login again')
                    next({path: '/login'})
                })
            } else {
                // 没有动态改变权限的需求可直接next() 删除下方权限判断 ↓
                if (hasPermission(store.getters.roles, to.meta.roles)) {
                    next()//
                } else {
                    next({ path: '/404', replace: true, query: { noGoBack: true }})
                }
            }
        }
    } else {

        if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            next('/login')
            NProgress.done()
        }
    }
})


router.afterEach(() => {
    NProgress.done()
})




